package com.jeeplus.modules.guide.web;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.modules.guide.service.DockingOtherService;
import com.jeeplus.modules.guide.service.MobileIndexService;
import com.jeeplus.modules.guide.utils.ImgUtils;
import com.jeeplus.modules.sys.entity.MobileUserQR;
import com.jeeplus.modules.sys.service.UserService;
import com.jeeplus.modules.sys.utils.FileKit;
import com.jeeplus.modules.sys.utils.UserUtils;
import lombok.RequiredArgsConstructor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.Base64;

@RestController
@RequestMapping("/docking")
@RequiredArgsConstructor
public class DockingOtherController {
    private static final Logger log = LoggerFactory.getLogger(DockingOtherController.class);
    private final DockingOtherService dockingOtherService;
    private final UserService userService;
    private final MobileIndexService mobileIndexService;
    //对接AppKeyValue
    @Value("${AppKeyValue}")
    private String AppKeyValue;
    /**
     * data base64
     *materialName 材料名称
     * materialType 材料类型
     * @return
     */
    @PostMapping(value = "intoElectronicMaterialFCAndXJH")
    public AjaxJson intoElectronicMaterialFCAndXJH(String data, String materialName, String materialType, String loginId, HttpServletRequest request){
        String  publicIp = UserUtils.getClientIpAddress(request);
        if(userService.checkUserIp(publicIp) <= 0){
            log.error("FCAndXJH事项材料非法ip:"+publicIp);
            return AjaxJson.error("非法ip:"+publicIp);
        }
        byte[] bytes = null;
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        File file = null;
        try{
            bytes = Base64.getDecoder().decode(data);
            String realPath = FileKit.getAttachmentDirYMBCSAll(loginId) + materialName+"."+materialType;
            file = new File(realPath);
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            if(materialName.contains("身份证")){
                dockingOtherService.intoElectronicMaterial(materialName, "/api/"+realPath.substring(realPath.indexOf("userfiles"),realPath.length()), materialType, loginId, "1",2);
            }else{
                dockingOtherService.intoElectronicMaterial(materialName, "/api/"+realPath.substring(realPath.indexOf("userfiles"),realPath.length()), materialType, loginId, "2",2);
            }
            return AjaxJson.success("操作成功！");
        }catch (Exception e){
            log.error("loginId:"+loginId+";error:"+e.getMessage());
            return AjaxJson.error("添加失败！");
        }finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }

    /**
     * data base64
     *materialName 材料名称
     * materialType 材料类型
     * @return
     */
    @GetMapping(value = "intoYmbcsFCAndXJH")
    public AjaxJson intoYmbcsFCAndXJH(String matterName, String area, String loginId, HttpServletRequest request){
        String  publicIp = UserUtils.getClientIpAddress(request);
        if(userService.checkUserIp(publicIp) <= 0){
            log.error("非法ip:"+publicIp);
            return AjaxJson.error("非法ip:"+publicIp);
        }
        //一码办成事 市场监管局人脸核身取证记录 一码申请量统计 事项名称为 营业执照发放
        MobileUserQR mu = userService.getUserIdcard(loginId);
        mobileIndexService.intoUserStreet(mu.getName(),mu.getIdcard(),mu.getTell(),matterName,area);
        return AjaxJson.success();

    }

    /**
     * data base64
     *materialName 材料名称
     * materialType 材料类型
     * @return
     */
    @PostMapping(value = "intoElectronicMaterial")
    public AjaxJson intoElectronicMaterial(HttpServletRequest request){
        String  publicIp = UserUtils.getClientIpAddress(request);
        if(userService.checkUserIp(publicIp) <= 0){
            log.error("区级事项材料非法ip:"+publicIp);
            return AjaxJson.error("非法ip:"+publicIp);
        }
        byte[] bytes = null;
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        File file = null;
        String str,materialName,materialType,url, body = "";
        try{
            BufferedReader reader = request.getReader();
            while((str = reader.readLine()) != null){
                body += str;
            }
            reader.close();
            body = JSONObject.fromObject(body.trim()).getString("response");
            String userId = JSONObject.fromObject(body).getJSONObject("user").getString("id");
            JSONArray entries = JSONObject.fromObject(body).getJSONArray("entries");
            for(int i =0;i<entries.size();i++){
                if(entries.getJSONObject(i).containsKey("attachment")){
                    materialName = entries.getJSONObject(i).getJSONObject("attachment").getString("name");
                    url = entries.getJSONObject(i).getJSONObject("attachment").getString("download_url");
                    materialType = materialName.substring(materialName.lastIndexOf(".")+1,materialName.length());
                    materialName = materialName.substring(0,materialName.lastIndexOf("."));
                    String realPath = FileKit.getAttachmentDirYMBCSAll(userId) + materialName+"."+materialType;
                    file = new File(realPath);
                    fos = new java.io.FileOutputStream(file);
                    bos = new BufferedOutputStream(fos);
                    bytes = ImgUtils.getData(url);
                    bos.write(bytes);
                    if(materialName.contains("身份证")){
                        dockingOtherService.intoElectronicMaterialGXID(materialName, "/api/"+realPath.substring(realPath.indexOf("userfiles"),realPath.length()), materialType, userId, "1",2);
                    }else{
                        dockingOtherService.intoElectronicMaterialGXID(materialName, "/api/"+realPath.substring(realPath.indexOf("userfiles"),realPath.length()), materialType, userId, "2",2);
                    }
                }
            }
            return AjaxJson.success("操作成功！");
        }catch (Exception e){
            log.error("result:"+body+";error:"+e.getMessage());
            return AjaxJson.error("添加失败！");
        }finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }
}
